package com.jblank.common.utils;

import java.util.List;
import java.util.Map;

import com.jblank.common.config.GlobalConfig;
import com.jblank.common.config.QueryConfig;
import com.jblank.common.config.TreeConfig;
import com.jblank.dao.Dao;
import com.jblank.dto.DTO;

/**
 * BusinessAction工具类
 * @author kim
 * @since 2013-08-08
 */
public class BusinessUtils {
	/**
	 * 按照ext数据返回树形json
	 * @param treeDto
	 * @param dao
	 * @return
	 */
	public static String queryTree(DTO treeDto,Dao dao) throws Exception{
		
		String parentId = treeDto.getAsString("parentId");
		int level = treeDto.getAsInteger("level");
		boolean isChecked = treeDto.getAsBoolean("isChecked");
		
		TreeConfig treeConfig = TreeConfig.transDtoToConfig(treeDto);
		QueryConfig queryConfig = QueryConfig.transDtoToConfig(treeDto);
		String queryCond = queryConfig.getCond();
		String tableName = queryConfig.getTableName();
		String flds = queryConfig.getFlds();
		String nodeFld = treeConfig.getNode_name();
		String idFld = treeConfig.getId();
		String nodeKindFld = treeConfig.getNode_kind();
		String orderFld = queryConfig.getOrder();
		
		if(idFld == null || idFld.length() == 0){
			idFld = GlobalConfig.TableMasterId;
		}
		
		if(flds != null && flds.length() > 0){
			flds += "," + idFld + "," + nodeFld;
		}else{
			flds = idFld + "," + nodeFld;
		}
		if(nodeKindFld != null && nodeKindFld.length() > 0){
			flds += "," + nodeKindFld;
		}
		List deptList;
		if(level == 0){
			String rootCond = treeConfig.getRoot_filter();
			if(queryCond != null && queryCond.length() > 0){
				queryCond += " and " + rootCond;
			}else{
				queryCond = rootCond;
			}
			deptList = dao.query(tableName,flds,queryCond,orderFld);
		}else{
			if(queryCond != null && queryCond.length() > 0){
				queryCond += " and "  + treeConfig.getParent() + " = ?";
			}else{
				queryCond = treeConfig.getParent() + " = ?";
			}
			deptList = dao.query(tableName,flds,queryCond,new String[]{parentId},orderFld);
		}
		for(int i = 0; i < deptList.size(); i++){
			Map p = (Map)deptList.get(i);
			String _id = (String) p.get(idFld);
			p.put("text", p.get(nodeFld));
			p.put("id", _id);
			//默认展开第一级，可扩展
			if(level == 0){
				p.put("expanded", true);
			}
			if(isChecked){
				p.put("checked", false);
			}
			if(nodeKindFld != null && nodeKindFld.length() > 0){
				String isLeaf = (String)p.get(nodeKindFld);
				p.put("leaf", isLeaf == GlobalConfig.IsLeaf);
			}else{
				String cond = treeConfig.getParent() + " = ? ";
				int count = dao.queryCount(tableName, cond,new String[]{_id});
				p.put("leaf", count == 0);
			}
		}
		return JsonHelper.encodeObject2Json(deptList);
	}
}
